package google.architecture.coremodel.viewmodel;

import android.app.Application;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;


import google.architecture.coremodel.R;
import google.architecture.coremodel.constant.ErrorCode;
import google.architecture.coremodel.datamodel.http.entities.BaseData;
import google.architecture.coremodel.datamodel.http.entities.ClassifyData;
import google.architecture.coremodel.datamodel.http.entities.LoginData;
import google.architecture.coremodel.datamodel.http.entities.ProductData;
import google.architecture.coremodel.datamodel.http.entities.TerInfoData;
import google.architecture.coremodel.navigator.ProductNavigator;
import google.architecture.coremodel.util.DeviceUtil;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 保存生命周期和UI所使用的数据
 * Created by dxx on 2017/11/10.
 */

public class ProductViewModel extends PayAndAddShopCarModel {
    private int mPage = 1;
    public final static int SIZE = 20;
    private Integer mTypeId = -1;
//    private String deviceId = "000000f2010ca7380149";
    private String deviceId = "";
    public ProductViewModel(@NonNull Application application) {
        super(application);
        String terMac = DeviceUtil.getMacAddress(application);
        if (!TextUtils.isEmpty(terMac) && !TextUtils.equals(terMac, "unknown")) {
            deviceId = terMac;
        } else {
            deviceId = DeviceUtil.getSerialNo();
        }
        Log.d(TAG, "deviceId=" + deviceId);
    }


    public int getPage() {
        return mPage;
    }

    public Integer getTypeId() {
        return mTypeId;
    }

    public void setTypeId(Integer typeId) {
        this.mTypeId = typeId;
    }

    public void setPage(int page) {
        this.mPage = page;
    }

    private ProductNavigator mNavigator;


    public void getTerNo() {
        getTerNo(true);
    }

    public void getTerNo(boolean needShowLoading) {
        if (needShowLoading && mNavigator != null) {
            mNavigator.showLoading();
        }
        mAutoVenderDataRepository.getTerInfo(deviceId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<TerInfoData>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(TerInfoData value) {
                        if (mNavigator != null) { TerInfoData.Data data = value.getData();
                            if (data == null || TextUtils.isEmpty(data.getTerNo())) {
                                mNavigator.showError(ErrorCode.FAILED_GET_TERNO, "该设备未注册，请联系管理员先注册！");
                                if (needShowLoading) {
                                    mNavigator.hideLoading();
                                }
                                return;
                            }
                            mNavigator.onReturnTerInfo(data);
                            getClassify(data.getTerNo());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError------>" + e.getMessage());
                        if (needShowLoading && mNavigator != null) {
                            mNavigator.hideLoading();
                        }
                        if (mNavigator != null)
                            mNavigator.showError(ErrorCode.FAILED_GET_TERNO, mContext.getString(R.string.network_error));
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        Log.i(TAG, "onComplete------>");

                    }
                });
    }

    public void loadData(String terNo) {
        loadData(terNo, false);
    }

    /**
     * @param terNo
     * @param needShowLoading 是否需要显示Loading
     */
    public void loadData(String terNo, boolean needShowLoading) {
        if (needShowLoading && mNavigator != null) {
            mNavigator.showLoading();
        }
        mAutoVenderDataRepository.getProductListRepository(mTypeId, terNo, mPage, SIZE)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ProductData>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(ProductData value) {
                        if (mNavigator != null)
                            mNavigator.showContent(value.getData(), mPage);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError------>" + e.getMessage());
                        if (needShowLoading && mNavigator != null) {
                            mNavigator.hideLoading();
                        }
                        if (mNavigator != null)
                            mNavigator.showError(ErrorCode.FAILED_GET_PRODUCT, mContext.getString(R.string.network_error));
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        if (needShowLoading && mNavigator != null) {
                            mNavigator.hideLoading();
                        }
                        Log.i(TAG, "onComplete------>");
                    }
                });
    }

    public void searchDrug(String words, String terNo) {
        mAutoVenderDataRepository.searchDrug(words, terNo, mPage, SIZE)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ProductData>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(ProductData value) {
                        if (mNavigator != null)
                            mNavigator.showContent(value.getData(), mPage);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError------>" + e.getMessage());
                        if (mNavigator != null)
                            mNavigator.showError(ErrorCode.FAILED_GET_PRODUCT, mContext.getString(R.string.network_error));
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        Log.i(TAG, "onComplete------>");
                    }
                });
    }


    public void getClassify(String terNo) {
        mAutoVenderDataRepository.getClassify(terNo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ClassifyData>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(ClassifyData value) {
                        if (mNavigator != null)
                            mNavigator.showClassify(value);
                        loadData(terNo, true);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError------>" + e.getMessage());
                        if (mNavigator != null) {
                            mNavigator.hideLoading();
                        }
                        if (mNavigator != null)
                            mNavigator.showError(ErrorCode.FAILED_GET_CLASSIFY, mContext.getString(R.string.network_error));
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        Log.i(TAG, "onComplete------>");
                    }
                });
    }

    public void verficatePwd(String terNo, String password, int todo) {
        if (mNavigator != null)
            mNavigator.showUnlockLoading();
        mAutoVenderDataRepository.login(terNo, password)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginData>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(LoginData value) {
                        if (value.getCode() == 200) {
                            if (value.isData()) {
                                Log.d(TAG, "解锁成功！");
                                mNavigator.onUnlocked(todo);
                            } else {
                                Log.e(TAG, "解锁密码错误！");
                                mNavigator.showError(ErrorCode.FAILED_UNLOCK, "解锁密码错误！");
                            }
                        } else {
                            Log.e(TAG, "服务器返回错误信息：code：" + value.getCode() + ",message:" + value.getMessage());
                            mNavigator.showError(ErrorCode.FAILED_UNLOCK, "解锁失败！");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (mNavigator != null)
                            mNavigator.hideUnlockLoading();
                        Log.e(TAG, "onError------>" + e.getMessage());
                        if (mNavigator != null)
                            mNavigator.showError(ErrorCode.FAILED_UNLOCK, mContext.getString(R.string.network_error));
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        mNavigator.hideUnlockLoading();
                        Log.i(TAG, "onComplete------>");
                    }
                });
    }


    public void putTerEnv(String terNo, int temp, int hum) {
        mAutoVenderDataRepository.putTerEnv(terNo, temp, hum)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseData value) {
                        if (value.getCode() == 200) {
                            Log.d(TAG, "温度上报成功---》温度:" + temp + ",湿度:" + hum);
                        } else {
                            Log.e(TAG, "温度失败----》服务器返回错误信息：code：" + value.getCode() + ",message:" + value.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError------>" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void saveMistake(String terNo, String errorCode) {
        mAutoVenderDataRepository.saveMistake(terNo, errorCode)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseData value) {
                        if (value.getCode() == 200) {
                            Log.d(TAG, "故障上报成功---》温度:"+errorCode);
                        } else {
                            Log.e(TAG, "故障上报失败----》服务器返回错误信息：code：" + value.getCode() + ",message:" + value.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError------>" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    public void tradeRefund(String tradeNo) {
        mAutoVenderDataRepository.tradeRefund(tradeNo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseData value) {
                        if (value.getCode() == 200) {
                            Log.d(TAG, "退款成功---》tradeNo:" + tradeNo);
                        } else {
                            mNavigator.onTradeRefundFailed();
                            Log.e(TAG, "退款失败---》服务器返回错误信息：code：" + value.getCode() + ",message:" + value.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mNavigator.onTradeRefundFailed();
                        Log.e(TAG, "退款失败---》" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    public void setProductNavigator(ProductNavigator navigator) {
        super.setNavigator(navigator);
        mNavigator = navigator;
    }
}
